<?php

session_start();
include "../include/config.php";
require_once('../includes_php/FirePHPCore-0.3.2/lib/FirePHPCore/fb.php');

fb('entro en el server_processing', 'PHP');

/* Database connection information */
$gaSql['user'] = DB_USER;
$gaSql['password'] = DB_PASS;
$gaSql['db'] = DB_NAME;
$gaSql['server'] = DB_HOST;

/* REMOVE THIS LINE (it just includes my SQL connection user/pass) */

//include( $_SERVER['DOCUMENT_ROOT']."/datatables/mysql.php" );


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
 * no need to edit below this line
 */

/*
 * Local functions
 */
function fatal_error($sErrorMessage = '') {
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
    die($sErrorMessage);
}

/*
 * MySQL connection
 */
if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
    fatal_error('Could not open connection to server');
}

if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
    fatal_error('Could not select database ');
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

/* Array of database columns which should be read and sent back to DataTables. Use a space where
 * you want to insert a non-database field (for example a counter or static image)
 */

/* DB table to use */
$sTable = "view_archivados";


$query = "DESCRIBE $sTable";
$result = mysql_query($query) or trigger_error(mysql_error());
$arrCampos = Array();

// $arrCampos = Array("","");
while ($row = mysql_fetch_array($result)) {
    $aColumns[] = $row['Field'];
}

//$aColumns = array( 'id_documentos', 'numero_ingreso', 'anio_ingreso', 'c_tipo_doc', 'remitente' );

/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id_documentos";




/*
 * Paging
 */
$sLimit = "";
if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
    $sLimit = "LIMIT " . mysql_real_escape_string($_GET['iDisplayStart']) . ", " .
            mysql_real_escape_string($_GET['iDisplayLength']);
}


//['iSortCol_0'] => 5
// mDataProp_
/*
 * Ordering
 */
$sOrder = "";
if (isset($_GET['iSortCol_0'])) {
    $sOrder = "ORDER BY  ";
    for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
        if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
            // $sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".
            // $sOrder .= "`".$aColumns[  ]."` ".

            $sOrder .= $_GET['mDataProp_' . intval($_GET['iSortCol_' . $i])] . " " .
                    mysql_real_escape_string($_GET['sSortDir_' . $i]) . ", ";
        }
    }

    $sOrder = substr_replace($sOrder, "", -2);
    if ($sOrder == "ORDER BY") {
        $sOrder = "";
    }
}


/*
 * Filtering
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here, but concerned about efficiency
 * on very large tables, and MySQL's regex functionality is very limited
 */
$sWhere = "";
if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
    $sWhere = "WHERE (";
    for ($i = 0; $i < count($aColumns); $i++) {
        if (($aColumns[$i] == "num_exp") || ($aColumns[$i] == "docNumAnio")) {
            //CONVERT( nro_exp USING utf8)
            $sWhere .= " CONVERT( " . $aColumns[$i] . " USING utf8) LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
        } else {
            $sWhere .= "`" . $aColumns[$i] . "` LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
        }
    }
    $sWhere = substr_replace($sWhere, "", -3);
    $sWhere .= ')';
}

fb($aColumns, 'PHP aColumns');
fb($_GET, 'PHP GET');

/* * ********************************************************************************************************** */
/* Individual column filtering */


// for ( $i=0 ; $i<count($aColumns) ; $i++ )
for ($i = 0; $i < $_GET['iColumns']; $i++) {
    if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {

        if ($sWhere == "") {
            $sWhere = "WHERE ";
        } else {
            $sWhere .= " AND ";
        }
        //$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
        //$sWhere .= "`".$aColumns[$i]."` = '".mysql_real_escape_string($_GET['sSearch_'.$i])."' ";
        //CAPAZ CONVENGA UNA VISTA CON TODO YA FORMATEADO!!!
        if ($_GET['mDataProp_' . $i] == "c_tipo_doc") {
            $sWhere .= "c_tipo_doc = '" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "' ";
        } else if ($_GET['mDataProp_' . $i] == "numero_ingreso") {
            $sWhere .= "numero_ingreso LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        } else if ($_GET['mDataProp_' . $i] == "c_estado_doc") {
            $sWhere .= "c_estado_doc = '" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "' ";
        } else if ($_GET['mDataProp_' . $i] == "docNumAnio") {
            $sWhere .= "CONVERT(docNumAnio USING utf8) LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        } else if ($_GET['mDataProp_' . $i] == "num_exp") {
            $sWhere .= "CONVERT(num_exp USING utf8) LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        } else {
            $sWhere .= "`" . $_GET['mDataProp_' . $i] . "` LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        }
    }
}


if ($sWhere == "") {
    $sWhere = " WHERE id_rep_dep_d = {$_SESSION['id_rep_dep_o']}";
} else {
    $sWhere .= " AND id_rep_dep_d = {$_SESSION['id_rep_dep_o']}";
}



fb($sWhere, 'PHP sWhere');

// ['mDataProp_0'] => 'id_documentos'
// ['mDataProp_1'] => 'c_estado_doc'
// ['mDataProp_2'] => 'numero_ingreso'
// ['mDataProp_3'] => 'nro_exp_judicial'
// ['mDataProp_4'] => 'fecha_alta'
// ['mDataProp_5'] => 'c_tipo_doc'
// ['mDataProp_6'] => 'remitente'
// ['mDataProp_7'] => 'caratula'
// ['mDataProp_8'] => 'id_rep_dep_mesa'
//['sSearch_0'] => 
//['sSearch_1'] => 'hola'
//['iColumns'] => 9
// for ( $i=0 ; $i< $_GET['iColumns'] ; $i++ )
// {
// }
/*
  if($_GET['sSearch_1'] != ""){ //c_estado_doc
  if ( $sWhere == "" )
  {
  $sWhere = "WHERE ";
  }
  else
  {
  $sWhere .= " AND ";
  }
  //$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
  $sWhere .= "`".$aColumns[$i]."` = '".mysql_real_escape_string($_GET['sSearch_1'])."' ";
  }
 */


/* * ********************************************************************************************************** */

/*
 * SQL queries
 * Get data to display
 */
$sQuery = "
		SELECT SQL_CALC_FOUND_ROWS `" . str_replace(" , ", " ", implode("`, `", $aColumns)) . "`
		FROM   $sTable
		$sWhere
		$sOrder
		$sLimit
		";
$rResult = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());

// fb($sQuery, 'PHP sQuery');

/* Data set length after filtering */
$sQuery = "
		SELECT FOUND_ROWS()
	";
$rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];

/* Total data set length */
$sQuery = "
		SELECT COUNT(`" . $sIndexColumn . "`)
		FROM   $sTable
	";
$rResultTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];


/*
 * Output
 */
$output = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
);

$arrTodo = array();

// while ( $aRow = mysql_fetch_array( $rResult ) )
// {
//$row = array();
// for ( $i=0 ; $i<count($aColumns) ; $i++ )
// {
// if ( $aColumns[$i] == "version" )
// {
// /* Special output formatting for 'version' column */
// $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
// }
// else if ( $aColumns[$i] != ' ' )
// {
// /* General output */
// $row[] = $aRow[ $aColumns[$i] ];
// }
// }


while ($row = mysql_fetch_array($rResult, MYSQL_ASSOC)) {//solo las claves
    $row = array_map("utf8_encode", $row);
    $arrTodo[] = $row;
}

$output['aaData'] = $arrTodo;
// }

echo json_encode($output);
?>